package cantools

import (
	"fmt"
	fd "gitee.com/CoolguyHolmes/socketcan-fd"
	"time"
)

type defaultSerialization struct {
	// 默认序列化为candump的log格式
	// 默认从candump的log格式反序列化
}

func (d *defaultSerialization) Serialize(frame *fd.RawFrame) string {
	return serialize(frame)
}

func (d *defaultSerialization) Deserialize(a string) *fd.RawFrame {
	return deserialize(a)
}

type Serialization interface {
	Serialize(frame *fd.RawFrame) string
	Deserialize(string) *fd.RawFrame
}

func serialize(f *fd.RawFrame) string {
	return fmt.Sprintf("(%10.6f) Can%d %X#%s\n",
		float64(time.Now().UnixNano())/1000000000, f.Interface, f.ArbId, bytes2string(f.Data[:f.Dlc]))
}

func bytes2string(a []byte) string {
	return fmt.Sprintf("%X", a)
}

//
func deserialize(a string) *fd.RawFrame {
	var timeStamp float64
	var canInterface, canId int32
	var data []byte

	_, err := fmt.Sscanf(a, "(%17f) Can%d %X#%X\n", &timeStamp, &canInterface, &canId, &data)
	if err != nil {
		fmt.Println("deserialize err: ", err)
	}
	ret := &fd.RawFrame{
		Interface: canInterface,
		ArbId:     canId,
		Time:      uint32(timeStamp), // TODO
		Dlc:       byte(len(data)),
		Extend:    false,
		Data:      [64]byte{},
	}
	copy(ret.Data[:], data)
	return ret
}
